import os
from uitls import *
import numpy as np
from pathlib import Path


def _save_data(cfg, brt):
    if cfg['Saving']['save_roi'] == '1':
        print('saving: ROI')
        save_path = cfg['Database']['data_path']+'//ROI_'
        if not os.path.exists(save_path):
            os.mkdir(save_path)
        save_data_batch.save_all_mat(brt, save_path, 'ROI', 0)

    if cfg['Saving']['save_mat'] == '1':
        print('saving: MAT')
        save_path = cfg['Database']['data_path']+'//MAT_'
        if not os.path.exists(save_path):
            os.mkdir(save_path)
        save_data_batch.save_all_mat(brt, save_path, 'MAT', 0)

    if int(cfg['Saving']['save_csv']) >= 1:
        print('saving: CSV')
        path_ori = cfg['Database']['data_path']
        item = Path(path_ori)
        save_path_ori = path_ori +'//CSV_ORI' # + datetime.today().strftime('%Y_%m_%d')
        if not os.path.exists(save_path_ori):
            os.mkdir(save_path_ori)
        else:
            # 需清空ori文件夹内的csv文件
            for filename in os.listdir(save_path_ori):
                file_path = os.path.join(save_path_ori, filename)
                try:
                    os.remove(file_path)
                except Exception as e:
                    print(f'删除{file_path}时出错：{e}')

        # save all files in the original dir to another dir
        for idx in item.iterdir():
            # get full new path/name
            name_new = save_path_ori + '/' + idx.name
            file_type = idx.name.split('.')[-1]
            if idx.is_file() and file_type == 'csv':
                idx.rename(name_new)
            else:
                print('')

        save_data_batch.save_all_mat(brt, path_ori, 'CSV', int(cfg['Saving']['save_csv']))
